package jk.fox.exchange.server;

import jk.fox.common.RpcDict;
import jk.fox.common.exception.runtime.RpcRunException;
import jk.fox.common.payload.request.Request;
import jk.fox.common.payload.response.RpcResponse;
import jk.fox.common.payload.server.Server;
import jk.fox.config.exchange.standard.DefaultExchangeConfiguration;
import jk.fox.engine.listener.RpcServiceStartedListener;
import jk.fox.exchange.server.handler.ExchangeHandler;
import jk.fox.transport.ServerTransporter;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cuichao
 * @Description: NettyServerExchange
 * @Date: create in 2020/4/14 14:53
 */
public class DefaultServerExchange implements ServerExchange {

    private static Logger logger = Logger.getLogger(DefaultServerExchange.class);

    private ServerTransporter transporter;
    private ExchangeHandler handler;
    private volatile Server server;
    private List<RpcServiceStartedListener> listeners = new ArrayList<>();
    private DefaultExchangeConfiguration configuration;


    public DefaultServerExchange(DefaultExchangeConfiguration config, ExchangeHandler handler, ServerTransporter transporter){
        this.configuration = config;
        this.handler = handler;
        this.transporter = transporter;
    }


    @Override
    public void bind(int port) {
        transporter.bind(port);
    }

    @Override
    public RpcResponse received(Request request) {
        RpcResponse response = null;
        logger.debug("ServerExchange received the request this requestId is "+ request.getRequestId());
        //执行前环绕可以埋点
        try {
             response = handler.handle(request);
            logger.debug("ServerExchange received the success request this requestId is "+ request.getRequestId());
        } catch (Exception e) {
            if(!(e instanceof RpcRunException)){
                e = new RpcRunException(e);
            }
            RpcRunException rpcException = (RpcRunException)e;
            response = new RpcResponse(request.getRequestId(),rpcException.getCode(),rpcException.getMessage());
            logger.error("ServerExchange received the exception request this requestId is "+ request.getRequestId(),e);
        }
        //执行后环绕可以埋点
        return response;
    }

    @Override
    public Server server() {
        return server;
    }

    @Override
    public void publishServer(Server server)  {
        this.server = server;
        //触发starter事件
        if(this.server.status() == RpcDict.NodeStatus.SUCCESS && server.address() != null){
            for (RpcServiceStartedListener listener : this.listeners) {
                listener.listen(server);
            }
        }
    }

    @Override
    public void addListener(RpcServiceStartedListener listener) {
        this.listeners.add(listener);
    }





}
